package systems;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import entities.Article;
import entities.ArticleSearch;

public class RecentlyArticle {
	
	private static String cacheName = "recently_article";
	
	private static int limit = 200;
	
	private static List<ArticleSearch> articles = null;
	
	private static Cache cache = null;
	
	public static void insert(Article article) {
		
		ArticleSearch articleSearch = ArticleSearch.convert(article);
		
		cache = GeneralHelper.getCache();
		
		if (cache != null && articles == null) {
			try {
				articles = (List<ArticleSearch>) cache.get(cacheName);
			} catch (Exception e) {
			}
		}
		
		if (articles == null) {
			articles = new ArrayList<ArticleSearch>();
		}
		
		for (int i = 0; i < articles.size(); i++) {
			if (articles.get(i).getId().equals(articleSearch.getId())) {
				articles.remove(articles.get(i));
			}
		}
		
		if (articles.size() >= limit) {
			articles.remove(limit - 1);
		}
		
		articles.add(0, articleSearch);
		
		cache.put(cacheName, articles);
	}
	
	public static void remove(Article article) {
		
		ArticleSearch articleSearch = ArticleSearch.convert(article);
		
		cache = GeneralHelper.getCache();
		
		if (cache != null && articles == null) {
			try {
				articles = (List<ArticleSearch>) cache.get(cacheName);
			} catch (Exception e) {
			}
		}
		
		if (articles == null) {
			articles = new ArrayList<ArticleSearch>();
		}
		
		for (int i = 0; i < articles.size(); i++) {
			if (articles.get(i).getId().equals(articleSearch.getId())) {
				articles.remove(articles.get(i));
			}
		}
		
		cache.put(cacheName, articles);
	}
	
	public static List<ArticleSearch> getArticles() {
		
		cache = GeneralHelper.getCache();
		
		if (cache != null && articles != null) {
			try {
				articles = (ArrayList<ArticleSearch>) cache.get(cacheName);
			} catch (Exception e) {
			}
		}
		
		if (articles == null) {
			articles = new ArrayList<ArticleSearch>();
		}
		
		return articles;
	}
}
